package com.tunnel.client.hendler;

import com.tunnel.client.processor.TransferProcessor;
import com.tunnel.common.protocol.Protocol;
import com.tunnel.common.protocol.ProtocolType;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 接收到服务端发来的数据时处理
 */
public class ClientTunnelHandler extends SimpleChannelInboundHandler<Protocol> {


    //handlerAdded 表示连接建立，一旦连接，第一个被执行
    //将当前channel 加入到  channelGroup
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "加入");

    }

    //断开连接, 将xx客户离开信息推送给当前在线的客户，该方法会自动将channel从channelGroup删除
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "离开");


    }

    //表示channel 处于活动状态, 提示 xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "上线");
    }

    //表示channel 处于不活动状态, 提示 xx离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "离线");
    }

    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Protocol protocol) throws Exception {
        // 指令类型
        int commonType = protocol.getCommonType();
        switch (commonType) {
            case ProtocolType.REGISTER:
                System.out.println("处理注册");
                break;
            case ProtocolType.HEARTBEAT:
                System.out.println("处理心跳");
                break;
            case ProtocolType.TRANSFER:

                TransferProcessor transferProcessor = new TransferProcessor();
                transferProcessor.process(ctx,protocol);
                break;
            case ProtocolType.CLOSE:
                System.out.println("客户端关闭");
                break;
        }
        System.out.println("读取到客户端消息");


    }

    // 发生异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}

